﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Threading;

/// <summary>
/// Summary description for ControlLog
/// </summary>
/// 

namespace ControlLogNamespace
{
    public delegate void delegateWriteLog(string strMessage);

    public class ControlLog
    {

        
        public ControlLog()
        {
        }

        public static void writeLogAsync(string strLogLine)
        {
            delegateWriteLog delegWriteLog = new delegateWriteLog(ControlLog.writeLog);
            IAsyncResult result= delegWriteLog.BeginInvoke(strLogLine, null, null);
            result.AsyncWaitHandle.WaitOne();
            delegWriteLog.EndInvoke(result);
            result.AsyncWaitHandle.Close();
        }
        

        public static void writeLog(string strLogLine)
        {
            Object thisLock = new Object();
            lock (thisLock)
            {
                try
                {
                    // Write the string to a file.
                    string saveDir = "\\\\hmfsw\\web\\DTCWIN155\\mymimportacionesweb.com.ar\\public_html\\Logs\\";
                    //   string saveDir = "H:\\logs\\";
                    //    string saveDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                    StreamWriter sw = File.AppendText(saveDir + "Log_" + System.DateTime.Now.Day.ToString().PadLeft(2, '0') + System.DateTime.Now.Month.ToString().PadLeft(2, '0') + System.DateTime.Now.Year.ToString() + ".log");

                    sw.WriteLine(System.DateTime.Now.ToString() + "|" + "Thread ID: " + Thread.CurrentThread.ManagedThreadId.ToString() + " - " + strLogLine);
                    // Writing a string directly to the file

                    sw.Close();
                }
                catch (IOException unEx)
                {
                    Random rndRandom = new Random();
                    Thread.Sleep(rndRandom.Next(10000));
                    ControlLog.writeLog(strLogLine);
                }
                catch (Exception ex)
                {
                    throw ex;

                }
            }
        }

        
        
    }
}